import os, json
from http.server import HTTPServer,BaseHTTPRequestHandler
from support.utils.toolkit import Log
from support.network.bilibili import Bilibili

class BilibiliHttpServer(HTTPServer):
    def run(port):
        try:
            server = BilibiliHttpServer(('0.0.0.0', port), BilibiliResquest)
            Log.i("Bilibili Server is running on [{}]".format(port))
            server.serve_forever()
        except Exception as e:
            Log.e(str(e))
            server.socket.close
            server.server_close
            
class BilibiliResquest(BaseHTTPRequestHandler):
    def log_message(self, format: str, *args):
        return

    def getLoginQRInfo(self):
        content = ""
        filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "bqr.base64")
        if(os.path.exists(filepath)):
            with open(filepath, 'r') as file:
                content = file.read()
        return content
    
    def do_GET(self):
        info = self.getLoginQRInfo()
        if(len(info)):
            contentType = "text/html"
            data = "<img src={} />".format(info)
        else:
            contentType = "application/json"
            data = "You have already logged in"
        self.send_response(200)
        self.send_header("Content-type",contentType)
        self.end_headers()
        if(contentType.endswith("json")):self.wfile.write(json.dumps(data).encode())
        if(contentType.endswith("html")):self.wfile.write(data.encode())
